package com;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;

import com.vo.User;

/**
 * Object Map 互相转换
 * @author litianyi
 *
 * 2015年10月26日
 */
public class ObjectToMap {

	
	public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException, InstantiationException {
		User user = new User();
		user.setId(1);
		user.setName("李");
		HashMap<String, Object> object2HashMap = object2HashMap(user);
	
		
		for(String key : object2HashMap.keySet()){
			
			System.out.println(key + ":" + object2HashMap.get(key));
			
		}
		
		user = hash2Object(object2HashMap, User.class);
		System.out.println(user.toString());
	}
	

	public static HashMap<String,Object> object2HashMap(Object obj) throws IllegalArgumentException, IllegalAccessException{
		
		HashMap<String, Object> map = new HashMap<String, Object>();
		
		Class clazz = obj.getClass();
		
		Field[] fields = clazz.getDeclaredFields();
		
		for(Field field : fields){
				field.setAccessible(true);
				map.put(field.getName(), field.get(obj));
		}
		
		 return map;
	}
	
	public static <T> T hash2Object(Map map,Class<T> clazz) throws InstantiationException, IllegalAccessException{
		T obj = clazz.newInstance();
		
		Field[] fields = clazz.getDeclaredFields();
		
		for(Field field : fields){
			int mod = field.getModifiers();    
            if(Modifier.isStatic(mod) || Modifier.isFinal(mod)){    
                continue;    
            }    
			 field.setAccessible(true);
			 field.set(obj, map.get(field.getName()));
		}
		return obj;
		
	}
	
}
